package com.ferreteria.zarate.dao.impl;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.SessionFactoryUtils;
import org.springframework.stereotype.Repository;

import com.ferreteria.zarate.dao.ClienteDao;
import com.ferreteria.zarate.model.Cliente;


@Repository
public class ClienteDaoImpl implements ClienteDao {

	private HibernateTemplate hibernateTemplate;
	private JdbcTemplate jdbcTemplate;
	
	
	@Autowired
	public ClienteDaoImpl(SessionFactory sessionFactory) {
		this.hibernateTemplate = new HibernateTemplate(sessionFactory);
		this.jdbcTemplate = new JdbcTemplate(SessionFactoryUtils.getDataSource(sessionFactory));
	}
	
	public void deleteCliente(Integer idCliente) {
		// TODO Auto-generated method stub
		Cliente cliente = getClienteById(idCliente);
		hibernateTemplate.delete(cliente);
	}
	
	public Cliente getClienteById(Integer idCliente) {
		// TODO Auto-generated method stub
		Cliente cliente = (Cliente) hibernateTemplate.get(Cliente.class, idCliente);
		return cliente;
	}
	
	@SuppressWarnings("unchecked")
	public List<Cliente> getClientesList(Cliente cliente) {
		// TODO Auto-generated method stub
		StringBuffer query = new StringBuffer(" from Cliente ");
		
		if(cliente != null && cliente.getNombre() != null 
				&& cliente.getNombre().length() > 0){
			
			query.append(" where upper(nombre) like '%").append(cliente.getNombre().
					toUpperCase()).append("%' ");
		}
		
		List<Cliente> list = (List<Cliente>)
				  hibernateTemplate.find(query.toString());
		return list;
	}

	public void saveCliente(Cliente cliente) {
		// TODO Auto-generated method stub
		hibernateTemplate.saveOrUpdate(cliente);
	}

	public boolean isRepeatDescription(String nombre, Integer idCliente) {
		// TODO Auto-generated method stub
		StringBuffer query = new StringBuffer();
		query.append("select count(*) from cliente ");
		query.append(" where upper(trim(nombre)) = '").append(nombre.trim().
				toUpperCase()).append("' ");
		
		if(idCliente != null){
			query.append(" and idCliente != ").append(idCliente);
		}		

		int count = jdbcTemplate.queryForInt(query.toString());
		if(count > 0){
			return true;
		}
		return false;
	}

}
